import { defineStore } from 'pinia'
import { useBoxStore } from './box.js'
import axios from 'axios'

export const useUserStore = defineStore('user', {
    state: () => {
        return {
            id: -1,
            is_load: false,
            is_auth: false
        }
    },
    actions: {
        login(email, password, callback) {
            // clear invalid tokens
            axios.defaults.headers.common.Authorization = ''
            // login
            axios
                .post(
                    'api/token/login/',
                    JSON.stringify({
                        email,
                        password
                    }),
                    {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                )
                .then((response) => {
                    const auth_token = response.data.auth_token
                    axios.defaults.headers.common['Authorization'] = 'Token ' + auth_token
                    this.$state.is_auth = true
                    // store
                    localStorage.setItem('auth_token', auth_token)
                    callback()
                    this.valid()
                })
                .catch((error) => {
                    const Box = useBoxStore()
                    Box.alert('error', 'Login Infomation', 'Invalid email or password!')
                })
        },
        signUp(email, password, re_password, callback) {
            axios
                .post(
                    'api/users/',
                    JSON.stringify({
                        email,
                        password,
                        re_password
                    }),
                    {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                )
                .then(() => {
                    // Authorization
                    callback()
                })
                .catch(() => {
                    const Box = useBoxStore()
                    Box.alert('error', 'Sign Up Infomation', 'email has been registed!')
                })
        },
        logout(callback) {
            axios
                .post('api/token/logout/')
                .then(() => {
                    this.$state.is_auth = false
                    axios.defaults.headers.common.Authorization = ''
                    localStorage.removeItem('auth_token')
                    const Box = useBoxStore()
                    Box.alert('success', 'Logout Infomation', 'successfully logout')
                    callback()
                })
                .catch(() => {
                    const Box = useBoxStore()
                    Box.alert('error', 'Logout Infomation', 'logout fail, please retry')
                })
        },
        async valid() {
            await axios
                .get('api/users/me/')
                .then((response) => {
                    this.id = response.data['id']
                    this.$state.is_auth = true
                })
                .catch(() => {
                    localStorage.removeItem('auth_token')
                })
        },
        async initialize() {
            const auth_token = localStorage.getItem('auth_token')
            if (!!auth_token) {
                // set token
                axios.defaults.headers.common['Authorization'] = 'Token ' + auth_token
                // check login state
                await this.valid()
            }
            this.$state.is_load = true
        },
        async passwdReset(email, password, callback, errorback) {
            const Box = useBoxStore()
            axios
                .post(
                    'api/password/reset/',
                    JSON.stringify({
                        email,
                        password
                    }),
                    {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                )
                .then((response) => {
                    Box.alert('success', 'Reset Password Infomation', 'successfully reset password')
                    callback(response)
                })
                .catch(() => {
                    Box.alert('error', 'Reset Password Infomation', 'reset password fail, please retry')
                    errorback()
                })
        },
        getProfile(callback, errorback) {
            const Box = useBoxStore()
            axios
                .get('api/profile/')
                .then((response) => {
                    callback(response.data)
                })
                .catch(() => {
                    errorback()
                    Box.alert('error', 'Get profile Infomation', 'get profile fail! Please try again!')
                })
        },
        updateProfile(modifyData, callback) {
            const Box = useBoxStore()
            axios
                .post('api/update-profile/', JSON.stringify(modifyData), {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(() => {
                    Box.alert('success', 'Update profile Infomation', 'successfully update profile!')
                    setTimeout(() => {
                        callback()
                    }, 500)
                })
                .catch(() => {
                    Box.alert('error', 'Update profile Infomation', 'email has been registed!')
                })
        },
        updateImage({ avator }, callback) {
            const Box = useBoxStore()
            axios
                .post(
                    'api/update-picture/',
                    {
                        avator: avator
                    },
                    {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                )
                .then(() => {
                    Box.alert('success', 'Upload picture Infomation', 'Successfully upload picture!')
                    setTimeout(() => {
                        callback()
                    }, 500)
                })
                .catch(() => {
                    Box.alert('error', 'Upload picture Infomation', 'upload fail! Please try again!')
                })
        }
    }
})
